<?php

class UserAction extends CommonAction{
    
    private $userdataKey = array('realname','nickname','photo','gender','birthday','address','job','exp','mobile','blog','major','weibo','school','xueli','shanchang','jineng','about');

    public function _empty() {
        $this->Page404();
    }
    
    //更新资料完整度
    private function updateInfopers(){
        $resUif = M('user_info')->where('uid='.$this->uid)->select();
        $total = $fillc = 0;
        foreach ($this->$userdataKey as $segkey) {
            $total++;
            if (!empty($resUif[$segkey])) {
                $fillc++;
            }
        }
        $pers = round($fillc/$total*100);
        M('account')->where('uid='.$this->uid)->setField('infopers', $pers);
    }
    
    private function ifActive()
    { //是否已经邮箱激活
        $account = M('account')->where('uid=' . $this->uid)->find();
        if ($account['emailverify'] == 0) {
            $this->redirect("Login/emailverify@".getDomain(), array('code'=>0));
            exit;
        }
    }

    protected function usermenuData()
    {
        $res = M('job_user')->table(array('xia_job_user' => 'jobuser', 'xia_job' => 'job', 'xia_team' => 'team', 'xia_project' => 'prj'))->field('jobuser.*, job.id, job.name as jname, team.name as tname')->where('jobuser.uid=' . $this->uid . ' and jobuser.state=2 and jobuser.jobid=job.id and job.pid=prj.id and prj.tid=team.id')->find();
//        Log::write($res, Log::ERR);
//        exit;
        if ($res) { //是职员
            $this->assign('menujob', $res);
        } else {
            $res2 = M('team')->where('uid=' . $this->uid . ' and state>0')->find();
            if ($res2) { //是否团队创建者
                $this->assign('menufounder', 1);
            }
        }
        $resAccount = M('account')->where('uid=' . $this->uid)->find();
        $this->assign('account', $resAccount);
    }

    //基本信息首页，对个人用户和企业用户转向
    public function info()
    {
        if ($this->userinfo['utype'] == 1) {
            $this->baseinfo();
        } else if ($this->userinfo['utype'] == 2) {
            $this->copinfo();
        }
    }

    public function favorites()
    {
        $tables = array('xia_project' => 'prj', 'xia_team' => 'team', 'xia_favorites' => 'fav', 'xia_user_info' => 'uif');
        $fields = 'prj.*,team.id as tid,team.id as tid,team.name as tname,team.logo,team.content,team.favcount,team.jobs,team.jobsok,fav.id as fid,uif.nickname as creater';
        $where = 'fav.pid=prj.id and team.id=prj.tid and fav.uid=' . $this->uid . ' and team.uid=uif.uid';
        //$fav = M('favorites')->table($tables)->field($fields)->where($where)->select();

        import('ORG.Util.Page'); // 导入分页类
        $count = M('favorites')->table($tables)->field($fields)->where($where)->count(); // 查询满足要求的总记录数
        $Page = new Page($count, 20); // 实例化分页类 传入总记录数
        // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        $nowPage = isset($_GET['p']) ? $_GET['p'] : 1;
        $fav = M('favorites')->table($tables)->field($fields)->where($where)->page($nowPage . ',' . $Page->listRows)->select();
        $show = $Page->show(); // 分页显示输出
        $this->assign('page', $show); // 赋值分页输出

        //dump($fav);
        $this->assign("fav", $fav);
        $this->assign("on", 4);
        $this->display();
    }

    //用户基本信息
    public function baseinfo()
    {
        $this->ifActive();
        //左侧导航数据
        $this->usermenuData();

        $new = 0;
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('new')) == true
            && I('new') == 1
        ) {
            $new = 1;
        }

        $where['uid'] = array('eq', $this->uid);
        $userinfo = M('user_info')->where($where)->find();
        $resUser = M('user')->where('id=' . $this->uid)->find();
        $userinfo['email'] = $resUser['email'];
        $degrees = M('dic')->where("type = 1")->select();
        $majors = M('dic')->where("type = 2")->select();
        $resPri = M('privacyflag')->where('uid='.$this->uid)->find();
        $this->assign("degrees", $degrees);
        $this->assign("majors", $majors);
        $this->assign("userinfo", $userinfo);
        $this->assign('priArr', $resPri);
        $this->assign("znav", 1); //左侧导航
        $this->display("baseinfo");
    }

    //企业基本信息
    public function copinfo()
    {
        $this->ifActive();
        $this->usermenuData();
        $this->assign("znav", 1); //左侧导航
        $this->display("copinfo");
    }


    //提交头像
    public function userphoto_ajax()
    {
        $photo = I('photo');
        $uid = $this->uid;
        $data = array(
            'photo' =>ltrim($photo,'/'),
            'uptime' => time(),
        );
        $arrsql = M('user_info');
        $arr = $arrsql->where("uid ='" . $uid . "'")->find();
        if ($arr) {
            if (strlen($arr['photo']) > 0) {
                if (!unlink($arr['photo'])) {
                    Log::write('[userphoto_ajax]删除旧头像文件' . $arr['photo'] . '失败!', Log::ERR);
                }
            }

            $resd = $arrsql->where("uid ='" . $uid . "'")->save($data);
            if ($resd) {
                $userinfo = $this->userinfo;
                $userinfo['photo'] = $photo;
                $userinfo['uptime'] = $data['uptime'];
                $this->userinfo = $userinfo;
                echo json_encode(array('success' => 1, 'msg' => ''));
                exit;
            } else {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        } else {
            $data['uid'] = $uid;
            $res = $arrsql->add($data);
            if ($res) {
                echo json_encode(array('success' => 1, 'msg' => ''));
                exit;
            } else {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        }
    }

    //提交基本信息
    public function userinfo_ajax()
    {
		$uid = $this->uid;
        //基本信息
        $realname = I('realname');
        $nickname = I('nickname');
        $gender = I('gender');
        $birthday = I('birthday'); //I('birthdayYear').'-'.I('birthdayMonth').'-'.I('birthdayDay');
        $address = I('address');
        $job = I('job');
        $exp = I('exp');
        $mobile = I('mobile');
		
        //$email   = I('email');
        $major = I('major');
        $blog = I('blog');
        $weibo = I('weibo');
        $school = I('school');
        $xueli = I('xueli');
        $shanchang = I('shanchang');
        //企业号
        $shortname = I('shortname');
        $industry = I('industry');
        $website = I('website');
		$telephone = I('telephone');
		$contactname = I('contactname');
		$contactemail = I('contactemail');
		$intro = I('intro');
		$culture = I('culture');
        $infodata = array(
            'realname' => $realname,
            'nickname' => $nickname,
            'gender' => $gender,
            'birthday' => $birthday,
            'address' => $address,
            'job' => $job,
            'exp' => $exp,
            'mobile' => $mobile,
            'major' => $major,
            'blog' => $blog,
            'weibo' => $weibo,
            'school' => $school,
            'xueli' => $xueli,
            'shanchang' => $shanchang,
            'uptime' => time(),
            'shortname' => $shortname,
            'companyname' => $nickname,
			'contactname'=>$contactname,
			'telephone'=>$telephone,
			'contactemail'=>$contactemail,
            'website' => $website,
            'industry' => $industry,
			'intro'=>$intro,
			'culture'=>$culture
        );
        
        //隐私控制
        $priData = array(
            'f_email' => I('f_email', 2),
            'f_realname' => I('f_realname', 2),
            'f_gender' => I('f_gender', 3),
            'f_birthday' => I('f_birthday', 2),
            'f_address' => I('f_address', 2),
            'f_job' => I('f_job', 2),
            'f_exp' => I('f_exp', 2),
            'f_mobile' => I('f_mobile', 2),
            'f_blog' => I('f_blog', 2),
            'f_major' => I('f_major', 2),
            'f_weibo' => I('f_weibo', 2),
            'f_school' => I('f_school', 2),
            'f_xueli' => I('f_xueli', 2),
            'f_shanchang' => I('f_shanchang', 2),
            'f_jianli' => I('f_jianli', 2),
            'f_works' => I('f_works', 2),
        );
        
        $arrsql = M('user_info');
        $arr = $arrsql->where("uid ='" . $uid . "'")->find();
        if ($arr) {
            if (isset($arr['realname']) && !empty($arr['realname'])) {
                unset($infodata['realname']);//已设置过真实姓名，不允许修改
            }
            $resd = $arrsql->where("uid ='" . $uid . "'")->save($infodata);
            if ($resd===false) {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            } else {
                //更新joib_user表的uname字段
                if ($nickname) {
                    M('job_user')->where('uid=' . $uid)->setField('uname', $nickname);
                }
                //更新类成员userinfo
                $userinfo = $this->userinfo;
                load("@.function");
                cloneByKey($infodata, $userinfo);
                $this->userinfo = $userinfo;
                //更新资料完整度
                $this->updateInfopers();
            }
        } else {
            $infodata['uid'] = $uid;
            $res = $arrsql->add($infodata);
            if (!$res) {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        }
        
        $tabPri = M('privacyflag');
        $resPri = $tabPri->where("uid='".$uid."'")->find();
        if ($resPri) {
            $resPri = $tabPri->where("uid='".$uid."'")->save($priData);
            if ($resPri===false) {
                ajaxf('保存隐私设置失败，请重新提交');
            }
        }
        else {
            $priData['uid'] = $uid;
            $resPri = $tabPri->add($priData);
            if (!$resPri) {
                ajaxf('保存隐私设置失败，请重新提交');
            }
        }
        ajaxs(1, '已保存基本信息设置');
    }

    //提交个人介绍
    public function userabout_ajax()
    {
        $about = I('about');
        $jineng = I('jineng');
        $uid = $this->uid;
        $data = array(
            'about' => qqTelFilter($about),
            'jineng' => qqTelFilter($jineng),
            'uptime' => time(),
        );
        //隐私设置
        $priData = array(
            'f_about' => I('f_about', 2),
            'f_jineng' => I('f_jineng', 2),
        );
        
        $arrsql = M('user_info');
        $arr = $arrsql->where("uid ='" . $uid . "'")->find();
        if ($arr) {
            $resd = $arrsql->where("uid ='" . $uid . "'")->save($data);
            if ($resd) {
                //更新资料完成度
                $this->updateInfopers();
            } else {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        } else {
            $data['uid'] = $uid;
            $res = $arrsql->add($data);
            if ($res) {
                //更新资料完成度
                $this->updateInfopers();
            } else {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        }
        $tabPri = M('privacyflag');
        $resPri = $tabPri->where("uid='".$uid."'")->find();
        if ($resPri) {
            $resPri = $tabPri->where("uid='".$uid."'")->save($priData);
            if ($resPri===false) {
                ajaxf('保存隐私设置失败，请重新提交');
            }
        }
        else {
            $priData['uid'] = $uid;
            $resPri = $tabPri->add($priData);
            if (!$resPri) {
                ajaxf('保存隐私设置失败，请重新提交');
            }
        }
        ajaxs(1, '已保存自我介绍和技能');
    }

    //简历信息
    public function userdetails()
    {
        $this->ifActive();
        //左侧导航数据
        $this->usermenuData();
        import('ORG.Util.Verify');
        $arr = M('jianli')->where("uid ='" . $this->uid . "'")->order('id desc')->select();
        foreach ($arr as $key => $value) {
            if (Verify::isEmpty($value['time']) == true) {
                $timearr = explode(',', $value['time']);
                $arr[$key]['btime'] = $timearr[0];
                $arr[$key]['etime'] = $timearr[1];
            }
        }
        $resPri = M('privacyflag')->where("uid='".$this->uid."'")->find();
        if ($resPri) {
            $this->assign('f_jianli', $resPri['f_jianli']);
        }
        $this->assign("arr", $arr);
        $this->assign("znav", 2); //左侧导航
        $this->display();
    }
    
    //简历信息隐私设置
    public function savejianlipri_ajax() {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('f_jianli'))==false) {
            ajaxf('参数错误');
        }
        $f_jianli = I('f_jianli');
        $tabPri = M('privacyflag');
        $resPri = $tabPri->where("uid='".$this->uid."'")->find();
        if ($resPri) {
            $resPri = $tabPri->where("uid='".$this->uid."'")->setField('f_jianli', $f_jianli);
            if ($resPri===false) {
                ajaxf('保存隐私设置失败,请重新尝试');
            }
        }
        else {
            $priArr = array(
                'uid' => $this->uid,
                'f_jianli' => $f_jianli,
            );
            $resPri = $tabPri->add($priArr);
            if (!$resPri) {
                ajaxf('保存隐私设置失败,请重新尝试');
            }
        }
        ajaxs(1, ''.$f_jianli);
    }

    //提交简历信息
    public function userdetails_ajax()
    {
        $company = I('company');
        $department = I('department');
        $position = I('position');
        $time = I('time');
        $content = I('content');
        $id = I('id');
        $uid = $this->uid;
        $data = array(
            'company' => $company,
            'department' => $department,
            'position' => $position,
            'time' => $time,
            'content' => $content,
            'uptime' => time(),
        );
        $arrsql = M('jianli');
        if ($id > 0) {
            $resd = $arrsql->where("id ='" . $id . "'")->save($data);
            if ($resd) {
                echo json_encode(array('success' => 1, 'msg' => ''));
                exit;
            } else {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        } else if ($id == 0) {
            $data['uid'] = $uid;
            $data['ctime'] = time();
            $res = $arrsql->add($data);
            if ($res) {
                echo json_encode(array('success' => 1, 'msg' => ''));
                exit;
            } else {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        }
    }

    //删除简历
    public function deljianli_ajax()
    {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('id')) == false) {
            echo json_encode(array('success' => 0, 'msg' => '参数错误！'));
            exit;
        }

        $id = I('id');
        $resJianli = M('jianli')->where('id=' . $id)->find();
        if ($resJianli['uid'] != $this->uid) {
            echo json_encode(array('success' => 0, 'msg' => '你不存在这样的一条简历！'));
            exit;
        }
        $ret = M('jianli')->where('id=' . $id)->delete();
        if ($ret) {
            echo json_encode(array('success' => 1, 'msg' => '已删除该简历'));
            exit;
        } else {
            echo json_encode(array('success' => 0, 'msg' => '删除失败！'));
            exit;
        }
    }
    
    //个人作品隐私设置
    public function saveworkspri_ajax() {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('f_works'))==false) {
            ajaxf('参数错误');
        }
        $f_works = I('f_works');
        $tabPri = M('privacyflag');
        $resPri = $tabPri->where("uid='".$this->uid."'")->find();
        if ($resPri) {
            $resPri = $tabPri->where("uid='".$this->uid."'")->setField('f_works', $f_works);
            if ($resPri===false) {
                ajaxf('保存隐私设置失败,请重新尝试');
            }
        }
        else {
            $priArr = array(
                'uid' => $this->uid,
                'f_works' => $f_works,
            );
            $resPri = $tabPri->add($priArr);
            if (!$resPri) {
                ajaxf('保存隐私设置失败,请重新尝试');
            }
        }
        ajaxs(1, ''.$f_works);
    }

    //图片作品
    public function works()
    {
        $this->ifActive();
        //左侧导航数据
        $this->usermenuData();

        $this->assign('worksetlist', 0);
        $this->assign('workset', 0);
        $worksetlist = M('workset')->where('uid=' . $this->uid)->order('ctime desc')->select();
//        dump($worksetlist);
//        exit;
        if ($worksetlist) {
            $this->assign('worksetlist', $worksetlist);
            $workset = M('work')->where("uid ='" . $this->uid . "' and wsid=" . $worksetlist[0]['id'] . " and wtype=1" . " and status=1")->order('ctime desc')->select();
            $this->assign('workset', $workset);
        }

//        dump($workset);
//        exit;
        $priArr = M('privacyflag')->where("uid='".$this->uid."'")->find();
        if ($priArr) {
            $this->assign('f_works', $priArr['f_works']);
        }

        $this->assign("znav", 3); //左侧导航
        $this->display('picture');
    }
    
    //获取用户所有作品集
    public function getworksets_ajax(){
        $datasource = M('workset')->where('uid=' . $this->uid)->order("ctime desc")->select();        
        if($datasource){
            $results = array();
            foreach($datasource as $item){
               $row = $item;
               $worklist = M('work')->where('uid=' . $this->uid . ' and wsid=' . $item["id"]. ' and status=1')->select();
               $row["total"] = count($worklist);
               $row["items"] = $worklist;
               $results[] = $row;
            }            
            echo json_encode($results);
            exit;
        }
        echo json_encode(array());
    }
    
    //获取用户单个作品集
    public function getworkset_ajax(){
       $wsid = I('id');
         $ws = M('workset')->where('uid=' . $this->uid.' and id='.$wsid)->find();
          echo json_encode($ws);
    } 
    
    //获取作品集下作品
    public function getworks_ajax()
    {
        $wsid = I('workset');
        if ($wsid <= 0) {
            $this->ajaxf('参数错误！');
        }

        $ws = M('workset')->where("id=".$wsid)->find();
        $worklist = M('work')->where('uid=' . $this->uid . ' and wsid=' . $wsid . ' and status=1')->select();
        //$this->ajaxs(1, json_encode($worklist));
        echo json_encode(array('success'=>1, 'ws'=>$ws, 'msg'=>json_encode($worklist)));
    }

    //添加/保存作品集信息
    public function addws_ajax()
    {
        $wsid = I('workset', 0);
        $wsname = I('name', '');
        $wsintro = I('intro', '');
        if ($wsname=='') {
            ajaxf('参数错误!');
        }

        $ws = array();
        $ws['name'] = $wsname;
        $ws['intro'] = $wsintro;
        
        if ($wsid == 0) {
            //是否超出限制,3个
            $resWs = M('workset')->where('uid=' . $this->uid)->count();
            if ($resWs >= 3) {
                $this->ajaxf('作品集数量已达上限');
            }
            
            //是否已有同名作品集
            $res = M('workset')->where("uid=".$this->uid." and name='".$wsname."'")->find();
            if ($res) {
                $this->ajaxf("你已创建过名称为".$wsname."的作品集，多个作品集名称不能相同");
            }

            $ws['uid'] = $this->uid;
            $ws['ctime'] = time();
            $wsid = M('workset')->add($ws);
            if ($wsid) {
                echo json_encode(array('success'=>1, 'ws'=>$wsid, 'wname'=>$wsname, 'wd'=>$wsintro, 'wn'=>$resWs+1));
            } else {
                $this->ajaxf('添加作品集失败！');
            }
        } else {
            $resWs = M('workset')->where('id=' . $wsid)->save($ws);
            if ($resWs) {
                $this->ajaxs(1);
            } else {
                $this->ajaxf('保存数据失败！');
            }
        }
    }

    //修改作品描述
    public function saveworkdesc_ajax()
    {
        $wid = I('work', 0);
        $desc = I('desc', '');
        if ($wid == 0 || $desc == '') {
            $this->ajaxf('参数错误!');
        } else {
            $ret = M('work')->where('id=' . $wid)->setField('description', $desc);
            if ($ret) {
                $this->ajaxs(1);
            } else {
                $this->ajaxf('保存作品描述失败！');
            }
        }
    }

    //删除作品集
    public function delws_ajax()
    {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('workset')) == false) {
            $this->ajaxf('参数错误！');
        }

        $wsid = I('workset');
        //删除集下的作品文件
        $wTab = M('work');
        $wsTab = M('workset');
        $resW = $wTab->where('uid=' . $this->uid . ' and wsid=' . $wsid . ' and wtype=1')->select();
        if ($resW) {
            //删除文件
            foreach ($resW as $work) {
                if (file_exists($work['pic_url'])) {
                    unlink($work['pic_url']);
                }
            }
            $retW = $wTab->where('uid=' . $this->uid . ' and wsid=' . $wsid . ' and wtype=1')->delete(); //删除作品记录
            if (!$retW) {
                $this->ajaxf('删除集下作品失败！');
            }

        }
        $retWs = $wsTab->where('id=' . $wsid . ' and uid=' . $this->uid)->delete(); //删除作品集记录
        if ($retWs) {
            $this->ajaxs(1);
        } else {
            $this->ajaxf('删除作品集失败！');
        }
    }

    //添加作品
    public function add_works()
    {
        $id = I('id', 0);
        if ($id > 0) {
            $arr = M('work')->where("id=" . $id . " and type=1 and status=1")->find();
        }
        $this->assign("id", $id);
        $this->assign("arr", $arr);
        $this->display('add_picture');
    }

    //提交作品信息
    public function add_works_ajax()
    {
        $type = I('type', 1);
        $title = I('title', '');
        $uid = $this->uid;
        $wsid = I('workset');

        $ret = M('work')->where('uid=' . $this->uid . ' and wsid=' . $wsid . ' and status=1')->count();
        if ($ret >= 5) {
            $this->ajaxf('作品数量超出限制');
        }

        $data = array();
        $filelist = I('filelist');
        if (!$filelist) {
            ajaxf('作品集已经创建，但没有上传作品');
        }
        foreach ($filelist as $file) {
            $filejson = htmlspecialchars_decode($file);
            $filej = json_decode($filejson, TRUE);
            $tempurl = $filej['uploadurl'];
            //文件转储
            $dir = 'Uploads/Pic_Userwork/'.date('Ymd');
            if (!file_exists($dir)) {
                mkdir($dir, 0777, true);
            }
            $url = $dir.'/'.basename($tempurl);
            if (!rename($tempurl, $url)) {
                Log::write('[add_works_ajax]文件转储失败:'.$tempurl.'=>'.$url, Log::ERR);
                $url = 'null';
            }
            unlink($tempurl);
            
            $data[] = array(
                'title' => $title,
                'description' => $filej['desc'],
                'pic_url' => $url,
                'uid' => $uid,
                'wsid' => $wsid,
                'wtype' => $type,
                'ctime' => time(),
            );
        }

        $arrsql = M('work');
        $res = $arrsql->addAll($data);
        if ($res) {
            echo json_encode(array('success' => 1, 'msg' => ''));
            exit;
        } else {
            echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
            exit;
        }
    }

    //删除作品
    public function del_work()
    {
        $id = I('work', 0);
        if ($id > 0) {
            $resWork = M('work')->where("id ='" . $id . "'")->find();
            if (!$resWork) {
                $this->ajaxf('找不到这个作品');
            }
            $res = M('work')->where("id ='" . $id . "'")->delete();
            if ($res) {
                unlink($resWork['pic_url']);
                echo json_encode(array('success' => 1, 'msg' => ''));
                exit;
            } else {
                echo json_encode(array('success' => 0, 'msg' => ''));
                exit;
            }
        } else {
            echo json_encode(array('success' => 0, 'msg' => ''));
            exit;
        }
    }

    //账户安全
    public function account()
    {
        //左侧导航栏数据
        $this->usermenuData();

        $isQp = 1;//是否设置密保问题
        $resProtect = M('pwdprotect')->where('uid=' . $this->uid)->select();
        if (!$resProtect) {
            $isQp = 0;
            $questions = M('dic')->where('type=5')->select();
            if ($questions) {
                $this->assign('qlist', $questions);
            }
        }
        $this->assign('isQp', $isQp);
        
        $ep = 0;//是否设置密保邮箱
        if (strlen($this->userinfo['protectemail'])>0) {
            $ep = 1;
        }
        $this->assign('ep', $ep);
        
        $this->assign('znav', 4);
        $this->display();
    }

    //绑定密保邮箱
    public function bindemail_ajax()
    {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('pemail')) == false) {
            echo json_encode(array('success' => 0, 'msg' => '邮箱地址不能为空!'));
            exit;
        }
        $pemail = I('pemail');

        $ret = M('user')->where("email='" . $pemail . "'")->find();
        if ($ret) {
            $this->ajaxf('这个邮箱地址已被用于注册账户，不能设置为密保邮箱!');
        }

        $resEmail = M('user_info')->where('uid=' . $this->uid)->setField('protectemail', $pemail);
        if ($resEmail) {
            $userinfo = $this->userinfo;
            $userinfo['protectemail'] = $pemail;
            $this->userinfo = $userinfo;
            echo json_encode(array('success' => 1, 'msg' => ''));
            exit;
        } else {
            echo json_encode(array('success' => 0, 'msg' => '绑定邮箱失败!'));
            exit;
        }
    }

    //校验Email地址是否已用于注册账户
    public function signup_checkProtectEmail()
    {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('txtEmail')) == false) {
            $this->ajaxf("参数错误！");
        }
        $email = I('txtEmail');
        $ret = M('user')->where("email='" . $email . "'")->find();
        if ($ret) {
            echo json_encode(FALSE);
        } else {
            echo json_encode(TRUE);
        }
    }

    //设置密保问题
    public function setprotectquestion_ajax()
    {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('q1')) == false
            || Verify::isEmpty(I('a1')) == false
            || Verify::isEmpty(I('q2')) == false
            || Verify::isEmpty(I('a2')) == false
        ) {
            echo json_encode(array('success' => 0, 'msg' => '数据出错!'));
            exit;
        }
        $qpTab = M('pwdprotect');
        $resQp = $qpTab->where('uid=' . $this->uid)->select();
        if ($resQp) {
            echo json_encode(array('success' => 0, 'msg' => '已设置过密保问题!'));
            exit;
        }

        $q1 = I('q1');
        $a1 = I('a1');
        $q2 = I('q2');
        $a2 = I('a2');

        $data = array();
        $data[] = array('uid' => $this->uid, 'qid' => $q1, 'answer' => $a1);
        $data[] = array('uid' => $this->uid, 'qid' => $q2, 'answer' => $a2);

        $resQp = $qpTab->addAll($data);
        if ($resQp) {
            echo json_encode(array('success' => 1, 'msg' => '成功设置密保问题!'));
            exit;
        } else {
            echo json_encode(array('success' => 0, 'msg' => '设置失败!'));
            exit;
        }
    }

    //修改密码
    public function changepwd_ajax()
    {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('oldpwd')) == false
            || Verify::isEmpty(I('newpwd')) == false
        ) {
            echo json_encode(array('success' => 0, 'msg' => '数据为空'));
            exit;
        }

        $oldpwd = md5(I('oldpwd'));
        $newpwd = md5(I('newpwd'));
        $userTab = M('user');
        $resUser = $userTab->where('id=' . $this->uid)->find();
        if (!$resUser) {
            echo json_encode(array('success' => 0, 'msg' => '未找到该用户!'));
            exit;
        }
        if ($oldpwd != $resUser['pwd']) {
            echo json_encode(array('success' => 0, 'msg' => '原始密码错误!'));
            exit;
        }
        $resUser = $userTab->where('id=' . $this->uid)->setField('pwd', $newpwd);
        if ($resUser) {
            echo json_encode(array('success' => 1, 'msg' => '重置密码成功'));
            exit;
        } else {
            echo json_encode(array('success' => 0, 'msg' => '重置密码失败'));
            exit;
        }
    }

    //催促审核
    public function blamecheck_ajax()
    {
        $eckTab = M('emecheck');
        $resEmecheck = $eckTab->where('uid=' . $this->uid)->find();
        if ($resEmecheck) {
            $data = array(
                'count' => $resEmecheck['count'] + 1,
            );
            $ret = $eckTab->where('uid=' . $this->uid)->save($data);
            if ($ret) {
                echo json_encode(array('success' => 1));
                exit;
            } else {
                echo json_encode(array('success' => 0, 'msg' => '催促失败，您可再次尝试!'));
                exit;
            }
        } else {
            $data = array(
                'uid' => $this->uid,
            );
            $ret = $eckTab->add($data);
            if ($ret) {
                echo json_encode(array('success' => 1));
                exit;
            } else {
                echo json_encode(array('success' => 0, 'msg' => '催促失败，您可再次尝试!'));
                exit;
            }
        }
    }

    //发送激活邮件
    public function sendVerify()
    {
        $Loginer = A('Login');
        $ret = $Loginer->recEmailVerify($this->user['nickname'], $this->uid, true);
        if ($ret) {
            $this->ajaxs(1, '已发送激活邮件，请去邮箱查收');
        } else {
            $this->ajaxf('未能成功发送激活邮件，请重新发送');
        }
    }
    
    //任职历史
    public function income() {
        //左侧导航栏数据
        $this->usermenuData();
        
        $table = array('xia_jobhistory'=>'jhis', 'xia_job'=>'job', 'xia_project'=>'prj', 'xia_team'=>'team', 'xia_user_info'=>'uif');
        $field = "jhis.jointime,jhis.quitime,jhis.quitype,jhis.income,job.id as jid,job.name as jname,job.salary,team.name as tname,team.uid as createrid,uif.nickname as creater";
        $where = "jhis.uid=".$this->uid." and jhis.jobid=job.id and jhis.prjid=prj.id and jhis.teamid=team.id and team.uid=uif.uid";
        $list = M('jobhistory')->table($table)->field($field)->where($where)->select();
        $total = 0;
//        dump($list);
//        exit;
        foreach ($list as $job) {
            $total += $job['income'];
        }
        $this->assign('totalIncome', $total);
        $this->assign('list', $list);
        
        $this->assign('znav', 5);
        $this->display();
    }
    
    //收藏的职位
    public function jobfav() {
        $table = array('xia_jobfav'=>'jf');
        $field = "j.*,team.name as tname, uif.nickname as creater";
        $join1 = "`xia_job` `j` ON jf.jobid=j.id";
        $join2 = "`xia_project` `prj` ON j.pid=prj.id";
        $join3 = "`xia_team` `team` ON prj.tid=team.id";
        $join4 = "`xia_user_info` `uif` ON uif.uid=team.uid";
        $where = "jf.uid=".$this->uid;
        import('ORG.Util.Page');// 导入分页类
        $count = M('jobfav')->table($table)->field($field)->join($join1)->join($join2)->join($join3)->join($join4)->where($where)->count();
        $Page = new Page($count,20);// 实例化分页类 传入总记录数
        // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        $nowPage = isset($_GET['p'])?$_GET['p']:1;
        $pageField = $field.",(SELECT COUNT(*) FROM `xia_jobfav` `njf` WHERE njf.jobid=j.id) as fc";
        $favs = M('jobfav')->table($table)->field($pageField)->join($join1)->join($join2)->join($join3)->join($join4)->where($where)->select();
        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
        //echo $favs;
        //exit;
        $this->assign('favs', $favs);
        $this->assign('tip', C('PRJ_MONEY_TUOGUAN_TIP_BROWSER'));
        $this->assign("on", 4);
        $this->display();
    }
    
    //查询信誉评价
    public function comments() {
        //左侧导航栏数据
        $this->usermenuData();
        
        import('ORG.Util.Page');// 导入分页类
        $tabUC = M('usercomment');
        $field = "xia_usercomment.*, (xia_usercomment.rate1+xia_usercomment.rate2+xia_usercomment.rate3+xia_usercomment.rate4)/4 as rate,job.name as jobname,uif.nickname as author";
        $join1 = "LEFT JOIN xia_user_info uif ON uif.uid=xia_usercomment.author";
        $join2 = "LEFT JOIN xia_job job ON job.id=xia_usercomment.job";
        if ($this->userinfo['utype']==1) {
            //雇主评价
            $rateArrL = $tabUC->query("SELECT ROUND(AVG(rate1)) AS avg1,ROUND(AVG(rate2)) AS avg2,ROUND(AVG(rate3)) AS avg3,ROUND(AVG(rate4)) AS avg4 FROM xia_usercomment WHERE ct=2 and uid=".$this->uid);//雇员评价
            //好评率,大于7分算好评
            $total = $tabUC->where("ct=2 and uid=".$this->uid)->count();
            $w1 = $tabUC->where("ct=2 and rate1>=7 and uid=".$this->uid)->count();
            $w2 = $tabUC->where("ct=2 and rate2>=7 and uid=".$this->uid)->count();
            $w3 = $tabUC->where("ct=2 and rate3>=7 and uid=".$this->uid)->count();
            $w4 = $tabUC->where("ct=2 and rate4>=7 and uid=".$this->uid)->count();
            $wellrateL = floor((($w1+$w2+$w3+$w4)/($total*4))*100);
            $this->assign('wellrateL', $wellrateL);
            $this->assign('ratearrL', $rateArrL[0]);
            //评价详情
            $where = "ct=2 and status=1 and xia_usercomment.uid=".$this->uid;
            $countL = $tabUC->where($where)->count();
            $pageL = new Page($countL, 100);
            $nowPageL = isset($_GET['p'])?$_GET['p']:1;
            $commentlistL = $tabUC->field($field)->join($join1)->join($join2)->where($where)->page($nowPageL.','.$pageL->listRows)->order("xia_usercomment.endate desc")->select();
    //        dump($commentlist);
    //        exit;
            $this->assign('commentsL', $commentlistL);
            $this->assign('pageL', $pageL->show());
        }
        
        //雇员评价
        $rateArrR = $tabUC->query("SELECT ROUND(AVG(rate1)) AS avg1,ROUND(AVG(rate2)) AS avg2,ROUND(AVG(rate3)) AS avg3,ROUND(AVG(rate4)) AS avg4 FROM xia_usercomment WHERE ct=1 and uid=".$this->uid);//雇主评价
        //好评率,大于7分算好评
        $total = $tabUC->where("ct=1 and uid=".$this->uid)->count();
        $w1 = $tabUC->where("ct=1 and rate1>=7 and uid=".$this->uid)->count();
        $w2 = $tabUC->where("ct=1 and rate2>=7 and uid=".$this->uid)->count();
        $w3 = $tabUC->where("ct=1 and rate3>=7 and uid=".$this->uid)->count();
        $w4 = $tabUC->where("ct=1 and rate4>=7 and uid=".$this->uid)->count();
        $wellrateR = floor((($w1+$w2+$w3+$w4)/($total*4))*100);
        $this->assign('wellrateR', $wellrateR);
        $this->assign('ratearrR', $rateArrR[0]);

        //评价详情
        $countR = $tabUC->where($where)->count();
        $pageR = new Page($countR, 100);
        $nowPageR = isset($_GET['p'])?$_GET['p']:1;
        $where = "ct=1 and status=1 and xia_usercomment.uid=".$this->uid;
        $commentlistR = $tabUC->field($field)->join($join1)->join($join2)->where($where)->page($nowPageR.','.$pageR->listRows)->order("xia_usercomment.endate desc")->select();
//        dump($commentlist);
//        exit;
        $this->assign('commentsR', $commentlistR);
        $this->assign('pageR', $pageR->show());
        
        $this->assign('znav', 6);
        $this->display();
    }
    
    //修改真实姓名
    public function changerealname_ajax() {
        $newname = I('newname');
        if (!$newname) {
            ajaxf("参数错误！");
        }
        $UserinfoDao = new UserInfoModel($this->uid);
        if ($UserinfoDao->changeRealname($newname)) {
            ajaxs();
        }
        else {
            ajaxf($UserinfoDao->getError());
        }
    }
}
